/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.product.web.product;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.CommonParameter;
import com.thinkgem.jeesite.common.utils.Message;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.product.entity.catalog.GenCatalog;
import com.thinkgem.jeesite.modules.product.entity.catalog.zTree;
import com.thinkgem.jeesite.modules.product.entity.product.GenProduct;
import com.thinkgem.jeesite.modules.product.service.catalog.GenCatalogService;
import com.thinkgem.jeesite.modules.product.service.product.GenProductService;
import com.thinkgem.jeesite.modules.shop.entity.info.ShopOrderInfo;
import com.thinkgem.jeesite.modules.shop.service.info.ShopOrderInfoService;
import com.thinkgem.jeesite.modules.shop.service.order.ShopOrderService;

/**
 * 商品管理Controller
 * @author Egan
 * @version 2016-12-12
 */
@Controller
@RequestMapping(value = "${adminPath}/product/product/genProduct")
public class GenProductController extends BaseController {

	@Autowired
	GenProductService genProductService;
	
	@Autowired
	GenCatalogService genCatalogService;
	
	@Autowired
	private ShopOrderInfoService shopOrderinfoService;
	
	@ModelAttribute
	public GenProduct get(@RequestParam(required=false) String id) {
		GenProduct entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = genProductService.get(id);
		}
		if (entity == null){
			entity = new GenProduct();
		}
		return entity;
	}
	
	@RequiresPermissions("product:product:genProduct:view")
	@RequestMapping(value = {"list", ""})
	public String list(GenProduct genProduct, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<GenProduct> page = genProductService.findPage(new Page<GenProduct>(request, response), genProduct); 
		model.addAttribute("page", page);
		return "modules/product/product/genProductList";
	}

	@RequiresPermissions("product:product:genProduct:view")
	@RequestMapping(value = "form")
	public String form(GenProduct genProduct, Model model) {
		
		List<GenCatalog> genCatalogs = genCatalogService.findList(null);
		model.addAttribute("genProduct", genProduct);
		model.addAttribute("path", CommonParameter.uploadPath);
		model.addAttribute("genCatalogs", genCatalogs);
		return "modules/product/product/genProductForm";
	}
	
	@RequiresPermissions("product:product:genProduct:view")
	@RequestMapping(value = "picture")
	public String picture(GenProduct genProduct, Model model) {
		
		String pictureStr = genProduct.getImages();
		if (!"".equals(pictureStr)) {
			String[] pictures = pictureStr.split(",");
			List<String> lst = Arrays.asList(pictures);
			
			model.addAttribute("path", CommonParameter.uploadPath);
			model.addAttribute("lst", lst);
		}
		genProduct.setDetail(StringEscapeUtils.unescapeHtml4(genProduct.getDetail().replaceAll("amp;", "")));
		model.addAttribute("genProduct", genProduct);
		return "modules/product/product/genProductPicture";
	}
	
	@RequiresPermissions("product:product:genProduct:view")
	@RequestMapping(value = "parameter")
	public String parameter(GenProduct genProduct, Model model) {
		if (genProduct.getDetail() != null) {
			genProduct.setDetail(StringEscapeUtils.unescapeHtml4(genProduct.getDetail().replaceAll("amp;", "")));
		}
		if (genProduct.getProducthtml() != null) {
			genProduct.setProducthtml(StringEscapeUtils.unescapeHtml4(genProduct.getProducthtml().replaceAll("amp;", "")));
		}
		model.addAttribute("genProduct", genProduct);
		return "modules/product/product/genProductParameter";
	}
	
	@RequiresPermissions("product:product:genProduct:view")
	@RequestMapping(value = "detail")
	public String detail(GenProduct genProduct, Model model) {
		if (genProduct.getDetail() != null) {
			genProduct.setDetail(StringEscapeUtils.unescapeHtml4(genProduct.getDetail().replaceAll("amp;", "")));
		}
		if (genProduct.getProducthtml() != null) {
			genProduct.setProducthtml(StringEscapeUtils.unescapeHtml4(genProduct.getProducthtml().replaceAll("amp;", "")));
		}
		model.addAttribute("genProduct", genProduct);
		return "modules/product/product/genProductDetail";
	}
	
	@RequiresPermissions("product:product:genProduct:view")
	@RequestMapping(value = "gif")
	public String gif(GenProduct genProduct, Model model) {
		if (genProduct.getDetail() != null) {
			genProduct.setDetail(StringEscapeUtils.unescapeHtml4(genProduct.getDetail().replaceAll("amp;", "")));
		}
		if (genProduct.getProducthtml() != null) {
			genProduct.setProducthtml(StringEscapeUtils.unescapeHtml4(genProduct.getProducthtml().replaceAll("amp;", "")));
		}
		model.addAttribute("genProduct", genProduct);
		
		if (!"".equals(genProduct.getCatalogid())) {
			List<GenProduct> products = genProductService.findListByCatalogId(genProduct.getCatalogid());
			model.addAttribute("products", products);
		}
		
		return "modules/product/product/genProductGif";
	}
	
	@RequiresPermissions("product:product:genProduct:view")
	@RequestMapping(value = "info")
	public String info(GenProduct genProduct, Model model) {
		String hitStr = genProduct.getHit();
		if (hitStr == null || "".equals(hitStr)) {
			genProduct.setHit("1");
		}
		else {
			genProduct.setHit(String.valueOf(Integer.parseInt(hitStr) + 1));
			
		}
		genProductService.save(genProduct);
		
		GenCatalog genCatalog = genCatalogService.get(genProduct.getCatalogid());
		genProduct.setCatalogName(genCatalog.getName());
		List<GenCatalog> genCatalogs = genCatalogService.findList(null);
		model.addAttribute("genProduct", genProduct);
		model.addAttribute("genCatalogs", genCatalogs);
		return "modules/product/product/genProductInfo";
	}
	
	@RequiresPermissions("product:product:genProduct:edit")
	@RequestMapping(value = "save")
	public String save(GenProduct genProduct, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, genProduct)){
			return form(genProduct, model);
		}
		genProductService.save(genProduct);
		
		addMessage(redirectAttributes, Message.getContent("genProduct.edit.success"));
		return "redirect:"+Global.getAdminPath()+"/product/product/genProduct/?repage";
	}
	
	@RequiresPermissions("product:product:genProduct:edit")
	@RequestMapping(value = "delete")
	public String delete(GenProduct genProduct, RedirectAttributes redirectAttributes) {
	    ShopOrderInfo shopOrderInfo = new ShopOrderInfo();
	    shopOrderInfo.setProductId(genProduct.getId());
	    List<ShopOrderInfo> list = shopOrderinfoService.findList(shopOrderInfo);
	    if(!list.isEmpty()){
	        addMessage(redirectAttributes, Message.getContent("genProduct.delete.error"));
	        return "redirect:"+Global.getAdminPath()+"/product/product/genProduct/?repage";
	    }
		genProductService.delete(genProduct);
		addMessage(redirectAttributes, Message.getContent("genProduct.delete.success"));
		return "redirect:"+Global.getAdminPath()+"/product/product/genProduct/?repage";
	}
	
	@RequiresPermissions("product:product:genProduct:view")
	@RequestMapping(value = "ztree")
	@ResponseBody
	public Object ztree(GenProduct genProduct, Model model) {
		
		List<GenCatalog> rootList = genCatalogService.findRootList(null);
		List<zTree> tree = new ArrayList<zTree>();
		
		for (int i = 0; i < rootList.size(); i ++) {
			GenCatalog menu = rootList.get(i);
			zTree ztree = new zTree();
			ztree.setId(String.valueOf(menu.getId()));
			ztree.setName(menu.getName());
			ztree.setParentId(String.valueOf(menu.getPid()));
			ztree.setOpen(false);
			ztree.setChecked(false);
			ztree.setChildren(getChildren(menu));
			tree.add(ztree);
		}
		return tree;
	}
	
	private List<zTree> getChildren(GenCatalog parentmenu) {
		
		List<GenCatalog> nextLevelList = genCatalogService.getNextLevelStep(parentmenu.getId());
		List<zTree> tree = new ArrayList<zTree>();
		
		for (int i = 0; i < nextLevelList.size(); i ++) {
			GenCatalog menu = nextLevelList.get(i);
			zTree ztree = new zTree();
			ztree.setId(String.valueOf(menu.getId()));
			ztree.setName(menu.getName());
			ztree.setParentId(String.valueOf(menu.getPid()));
			ztree.setOpen(false);
			ztree.setChecked(false);
			ztree.setChildren(getChildren(menu));
			tree.add(ztree);
		}
		return tree;
	}
	
	@RequestMapping(value = "upload")
	@ResponseBody
	public Object upload(MultipartHttpServletRequest request, HttpServletResponse response) {
		Map<String, MultipartFile> fileMap = request.getFileMap();
		
		Map<String, String> resultMap = new HashMap<String, String>();
        try {
            String dir = request.getSession().getServletContext().getRealPath("upload");
            File file = new File(dir);
            if (!file.exists()) {
                file.mkdirs();
            }
            String fileName = null;
    		File uploadFile = null;
            if (fileMap.entrySet().iterator().hasNext()) {
            	Map.Entry<String, MultipartFile> entity = fileMap.entrySet().iterator().next();
    			MultipartFile mf = entity.getValue();
    			// 上传文件的名称
    			fileName = mf.getOriginalFilename();
//    			// 文件格式
//    			String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
//    			newFileName = fileName;
//    			// 根据当前日期进行重命名
//				SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
//				newFileName = df.format(new Date())+ "_"+ new Random().nextInt(1000)+ "."+ fileExt;
    			uploadFile = new File(dir +File.separator+ fileName);
    			
    			FileCopyUtils.copy(mf.getBytes(), uploadFile);
            }
            resultMap.put("fileName", fileName);
            resultMap.put("result", "success");
            resultMap.put("filePath",CommonParameter.uploadPath +File.separator+ fileName);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", "failure");
        }
        return resultMap;
	}
	@RequiresPermissions("product:product:genProduct:edit")
	@RequestMapping(value = "shelve")
	@ResponseBody
	public Object shelve( @ModelAttribute("id") String id, @ModelAttribute("status") String status,
			Model model, RedirectAttributes redirectAttributes) {
		GenProduct genProduct = new GenProduct();
		genProduct.setId(id);
		genProduct.setStatus(status);
		genProductService.updateStatus(genProduct);
		Map<String,String> resultMap = new HashMap<String,String>();
		resultMap.put("message", Message.getContent("genProduct.status.edit"));
		return resultMap;
	}
}